Skip to main content

How to develop a Linux Kernel Module

Linux is one of the most known and used Operating systems. In this post, I am going to explain the required steps to develop a Linux Kernel Module (LKM) For the demonstration, I am going to use a Ubuntu 14.04 server hosted on Microsoft Azure.

First you need to prepare the environment and make sure that you installed "build-essential" sudo apt-get install build-essential

Install the "Linux headers" sudo apt-get install linux-headers-'uname -r'

Enter /usr/src and create a c file and insert the following code:

Name it linux_module.c #include <linux/init.h> #include <linux/module.h> #include <linux/kernel.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Chiheb Chebbi"); MODULE_DESCRIPTION("This is a Demo for a Linux module."); MODULE_VERSION("0.01"); static int init linux_module_init(void) { printk(KERN_INFO "Hello, Peerlysters!\n"); return 0; } static void exit linux_module_exit(void) { printk(KERN_INFO "Goodbye, Peerlysters!\n"); } module_init(linux_module_init); module_exit(linux_module_exit); for the demo, I used "vi" . As you can see from the c program, Linux kernel modules usually include 2 elements: init(constructor)and exit(destructor). In addition of the Module information (LICENSE, DESCRIPTION and so on) we simply used a print command to result "Hello Peerlysters!" when the module is deployed into kernel address space.

Create a makefile (use Tabs before make instead of spaces): obj-m += linux_module.o all: make -C /lib/modules/4.15.0-1031-azure/build M=/usr/src/ modules clean: make -C /lib/modules/4.15.0-1031-azure/build M=/usr/src/ clean

Your module will be compiled successfully

To add it you just need to use insmod

sudo insmod linux_module.ko

To check the message "Hello Peerlysters!" run dmesg

sudo dmesg

By now you learned the required steps to build a simple Linux Kernel Module (LKM) Further readings: https://blog.sourcerer.io/writing-a-simple-linux-kernel-module-d9dc3762c234 http://derekmolloy.ie/writing-a-linux-kernel-module-part-1-introduction/ Mastering Linux Kernel Development